<?php

class ContentPageModel extends Model
{
    /**
     * 使用的表名称.
     *
     * @var string
     */
    protected $tableName = 'content_stats';
    /**
     * 初始化方法，数据库配置、连接初始化.
     */
    public function __construct()
    {
        $dbconfig = array();
        $_config = C('ONLINE_DB');
        $dbconfig['DB_TYPE'] = isset($_config['DB_TYPE']) ? $_config['DB_TYPE'] : C('DB_TYPE');
        $dbconfig['DB_HOST'] = isset($_config['DB_HOST']) ? $_config['DB_HOST'] : C('DB_HOST');
        $dbconfig['DB_NAME'] = isset($_config['DB_NAME']) ? $_config['DB_NAME'] : C('DB_NAME');
        $dbconfig['DB_USER'] = isset($_config['DB_USER']) ? $_config['DB_USER'] : C('DB_USER');
        $dbconfig['DB_PWD'] = isset($_config['DB_PWD']) ? $_config['DB_PWD'] : C('DB_PWD');
        $dbconfig['DB_PORT'] = isset($_config['DB_PORT']) ? $_config['DB_PORT'] : C('DB_PORT');
        $dbconfig['DB_PREFIX'] = isset($_config['DB_PREFIX']) ? $_config['DB_PREFIX'] : C('DB_PREFIX');
        $dbconfig['DB_CHARSET'] = isset($_config['DB_CHARSET']) ? $_config['DB_CHARSET'] : C('DB_CHARSET');

        $db_pwd = $dbconfig['DB_PWD'];

        if ($dbconfig['DB_ENCRYPT'] == 1) {
            if ($db_pwd != '') {
                require_once SITE_PATH.'/addons/library/CryptDES.php';
                $crypt = new CryptDES();
                $db_pwd = (string) $crypt->decrypt($db_pwd);
            }
        }
        // 重设Service的数据连接信息
        $connection = array(
            'dbms'     => $dbconfig['DB_TYPE'],
            'hostname' => $dbconfig['DB_HOST'],
            'hostport' => $dbconfig['DB_PORT'],
            'database' => $dbconfig['DB_NAME'],
            'username' => $dbconfig['DB_USER'],
            'password' => $db_pwd,
        );
        // 实例化Online数据库连接
        $this->odb = new Db($connection);
        $this->today = date('Y-m-d');
        $this->todayTimestamp = strtotime(date('Y-m-d'));
    }
    /**
     * 字段列表.
     *
     * @var unknown_type
     */
    protected $fields = array(
        0          => 'id',
        1          => 'day',
        2          => 'new_users',
        3          => 'active_guests',
        '_autoinc' => true,
        '_pk'      => 'id',
    );


    /**
     * 获取统计列表.
     *
     * @param string $where 查询条件
     * @param int    $limit 结果集数目，默认为30
     *
     * @return array 统计列表数据
     */
    public function getContentPageList($where = '1', $limit = 30)
    {
        $p = $_REQUEST['p'] ? $_REQUEST['p'] : 1;
        $start = ($p - 1) * $limit;
        $sqlCount = 'SELECT COUNT(1) as count FROM '.C('DB_PREFIX')."content_stats WHERE {$where} ";
        if ($count = $this->odb->query($sqlCount)) {
            $count = $count[0]['count'];
        } else {
            $count = 0;
        }

        $sql = 'SELECT * FROM '.C('DB_PREFIX')."content_stats WHERE {$where} order by id desc LIMIT $start,$limit";

        $data = $this->odb->query($sql);

        $p = new Page($count, $limit);
        $output['count'] = $count;
        $output['totalPages'] = $p->totalPages;
        $output['totalRows'] = $p->totalRows;
        $output['nowPage'] = $p->nowPage;
        $output['html'] = $p->show();
        $output['data'] = $data;

        return $output;
    }
    /**
     * 获取状态
     *
     * @param int $state 状态ID
     *
     * @return mixed
     */
    public function getState($state = null)
    {
        $states = array(
            1 => '显示',
            0 => '不显示',
        );
        if ($state === null) {
            return $states;
        }

        return isset($states[$state]) ? $states[$state] : '';
    }


    /**
     * 前台列表获取.
     */
    public function getList($limit = 20, $order = '', $findPage = true)
    {
        $map = array();
        $map['state'] = array('GT', 0);

        if ($order == '') {
            $order = 'sort desc,id desc';
        }

        $this->where($map)->order($order);
        if ($findPage) {
            $list = $this->findPage($limit);
            $data = $list['data'];
        } else {
            $data = $this->findAll(array('limit' => $limit));
        }
        foreach ($data as $k => $v) {
            $thumb = APPS_URL.'/'.APP_NAME.'/_static/nopic.jpg';

        }
        if ($findPage) {
            $list['data'] = $data;

            return $list;
        } else {
            return $data;
        }
    }

    /**
     * 根据ID获取资料.
     *
     * @param int  $id
     * @param bool $is_admin 是否是后台
     *
     * @return array
     */
    public function getOneyById($id, $is_admin = false, $update_hits = false)
    {
        $map = array(
            'design_id' => $id,
        );
        if ($is_admin == false) {
            $map['state'] = array('GT', 0);
        }
        $v = $this->where($map)->find();
        if ($v) {
            $v['attachId'] = $v['picture'];
            $thumb = APPS_URL.'/'.APP_NAME.'/_static/nopic.jpg';
            if ($v['image']) {
                $attach = model('Attach')->getAttachById($v['picture']);
                if ($attach) {
                    $thumb = getImageUrl($attach['save_path'].$attach['save_name'], 100, 100);
                }
            }
            $v['picture'] = $thumb;
            //更新浏览量
            if ($is_admin === false && $update_hits == true) {
                $this->setInc('hits', array('design_id' => $id), 1);
            }
        }

        return $v;
    }

    /**
     * 获取子分类的ID串.
     *
     * @param int $pid
     *
     * @return array
     */
    private function getChildTids($pid)
    {
        static $_result = array();
        if (isset($_result[$pid])) {
            return $_result[$pid];
        }
        //查找
        $child = model('CategoryTree')->setTable('news_category')->getNetworkList($pid);
        $ids = array_keys($child);
        $_result[$pid] = ($ids) ? $ids : array();

        return $ids;
    }

    /**
     * 获取信息.
     *
     * @param int $id
     *
     * @return mixed
     */
    public function getSourceInfo($id)
    {
        $find = $this->getOneyById($id);
        if ($find) {
            $info = array('source_user_info' => '');
            if ($find['uid']) {
                $info['source_user_info'] = model('User')->getUserInfo($find['uid']);
            }
            $info['source_url'] = U('news/Index/detail', array('id' => $id));
            $info['source_body'] = $find['news_title'].'<a class="ico-details" href="'.U('news/Index/show', array('id' => $id)).'"></a>';

            return $info;
        }

        return false;
    }

    /**
     * 删除分类后的回调.
     *
     * @param int $cid
     *
     * @return bool
     */
    public function deleteAssociatedData($cid)
    {
        return $this->where(array('type_id' => $cid))->delete();
    }
}
